package com.bdbit.ChargingStation.services.impl;

import com.bdbit.ChargingStation.services.MqttMessageService;
import com.bdbit.ChargingStation.services.PaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
public class ChargingServiceImpl implements MqttMessageService {

    private static final Logger log = LoggerFactory.getLogger(ChargingServiceImpl.class);

    // @Autowired  // 删除或注释掉这一行
    
    // ICCID 和 IMEI
    //@Value("${charging.iccid}")
    //private String iccid;
    
    //@Value("${charging.imei}")
    //private String imei;
    
    // 设备状态管理
    private final Map<String, DeviceState> deviceStates = new ConcurrentHashMap<>();
    
    // 充电功率监控执行器
    private final ScheduledExecutorService powerMonitorExecutor = Executors.newScheduledThreadPool(5);
    
    @Autowired
    private PaymentService paymentService;

    @Override
    public String processMessage(String topic, String payload) {
        log.info("收到消息 - 主题: {}, 内容: {}", topic, payload);
        
        // 1. 处理心跳包和注册包
        if (topic.equals(payload.trim())) {
            handleHeartbeat(payload);
            return null;
        }

        
        // 2. 处理设备上报事件
        if (topic != null) {
            String[] parts = payload.split("\\.");
            if (parts.length < 2) return null;
            
            String eventType = parts[1].trim().toLowerCase();
            return handleDeviceEvent(eventType, payload);
        }
        // 3. 处理付款指令
        return handlePaymentInstruction(payload);
    }
    
    // 处理心跳包
    private void handleHeartbeat(String payload) {
        String deviceId = payload.trim();
        log.info("设备 {} 心跳正常", deviceId);
        
        // 更新设备最后活动时间
        DeviceState state = deviceStates.computeIfAbsent(deviceId, k -> new DeviceState());
        state.setLastHeartbeat(System.currentTimeMillis());
    }
    
    // 处理设备事件
    private String handleDeviceEvent(String eventType, String payload) {
        switch (eventType) {
            case "overload":
                return handleOverload(payload);
            case "noload":
                return handleNoLoad(payload);
            case "charing":
                return handleCharging(payload);
            case "changed":
                return handleChanged(payload);
            case "errordone":
                return handleErrorDone(payload);
            case "done":
                return handleDone(payload);
            default:
                log.warn("未知事件类型: {}", eventType);
                return null;
        }
    }
    
    // 处理过载事件
    private String handleOverload(String payload) {
        log.warn("设备过载警告: {}", payload);
        String deviceId = payload.split("\\.")[0];
        deviceStates.get(deviceId).setStatus(DeviceStatus.OVERLOAD);
        
        // 触发断电操作
        cutOffPower(deviceId);
        
        // 退款处理
        paymentService.processRefund(deviceId);
        return null;
    }
    
    // 处理无负载事件
    private String handleNoLoad(String payload) {
        log.warn("设备无负载警告: {}", payload);
        String deviceId = payload.split("\\.")[0];
        deviceStates.get(deviceId).setStatus(DeviceStatus.NO_LOAD);
        
        // 触发断电操作
        cutOffPower(deviceId);
        
        // 退款处理
        paymentService.processRefund(deviceId);
        return null;
    }
    
    // 处理充电事件
    private String handleCharging(String payload) {
        log.info("设备充电状态: {}", payload);
        String[] parts = payload.split("\\.");
        if (parts.length < 3) return null;
        
        String deviceId = parts[0];
        long chargingTime = Long.parseLong(parts[2].replaceAll("\\D", ""));
        
        DeviceState state = deviceStates.get(deviceId);
        state.setChargingTimeLeft(chargingTime);
        state.setStatus(DeviceStatus.CHARGING);
        
        // 更新充电桩状态为"使用中"
        try {
            //chargingPileRepository.updateOperationStatus(deviceId, "in_use");
            log.info("充电桩状态已更新为使用中: {}", deviceId);
        } catch (Exception e) {
            log.error("更新充电桩状态失败: {}", deviceId, e);
        }
        
        // 30秒内监控功率
        powerMonitorExecutor.schedule(() -> {
            int power = state.getCurrentPower();
            
            // 检查功率是否超过1800W
            if (power > 1800) {
                String overloadMsg = String.format("%s.overload\r\n", deviceId);
                log.warn("功率过载: {}W, 发送消息: {}", power, overloadMsg);
                cutOffPower(deviceId);
                return;
            }
            
            // 检查功率是否小于30W
            if (power < 30) {
                String noLoadMsg = String.format("%s.NoLoad\r\n", deviceId);
                log.warn("无负载: {}W, 发送消息: {}", power, noLoadMsg);
                cutOffPower(deviceId);
                return;
            }
            
            // 功率正常，计算充电时间
            log.info("功率正常: {}W, 开始充电", power);
            String chargingMsg = String.format("%s.charing.%d\r\n", deviceId, chargingTime);
            log.info("发送充电信息: {}", chargingMsg);
            
            // 监控功率变化
            monitorPowerChange(deviceId, power);
        }, 30, TimeUnit.SECONDS);
        
        return null;
    }
    
    // 处理设备更换事件
    private String handleChanged(String payload) {
        log.warn("设备更换警告: {}", payload);
        String deviceId = payload.split("\\.")[0];
        deviceStates.get(deviceId).setStatus(DeviceStatus.CHANGED);
        
        // 停止供电
        stopPowerSupply(deviceId);
        return null;
    }
    
    // 处理异常结束事件
    private String handleErrorDone(String payload) {
        log.warn("充电异常结束: {}", payload);
        String deviceId = payload.split("\\.")[0];
        DeviceState state = deviceStates.get(deviceId);
        state.setStatus(DeviceStatus.ERROR_DONE);
        
        // 检查60秒内恢复
        powerMonitorExecutor.schedule(() -> {
            if (state.getStatus() != DeviceStatus.CHARGING) {
                cutOffPower(deviceId);
                paymentService.processRefund(deviceId);
            }
        }, 60, TimeUnit.SECONDS);
        return null;
    }
    
    // 处理正常结束事件
    private String handleDone(String payload) {
        log.info("充电正常结束: {}", payload);
        String deviceId = payload.split("\\.")[0];
        DeviceState state = deviceStates.get(deviceId);
        state.setStatus(DeviceStatus.DONE);
        
        // 新增：更新充电桩状态为"空闲"
        try {
            //chargingPileRepository.updateOperationStatus(deviceId, "idle");
            log.info("充电桩状态已更新为空闲: {}", deviceId);
        } catch (Exception e) {
            log.error("更新充电桩状态失败: {}", deviceId, e);
        }
        
        // 断电
        cutOffPower(deviceId);
        return null;
    }
    
    // 处理付款指令
    private String handlePaymentInstruction(String payload) {
        log.info("处理付款指令: {}", payload);
        
        // 解析付款信息 (格式: IMEI.充电时长乘10.00)
        String[] parts = payload.split("\\.");
        if (parts.length != 3) {
            log.error("无效的付款格式: {}", payload);
            return "ERROR|无效格式";
        }
        
        try {
            String targetDevice = parts[0].trim();
            String durationPart = parts[1].trim();
            String lastPart = parts[2].trim();
            
            // 确认是第二种模式: IMEI.充电时长乘10.00
            if (!lastPart.equals("00")) {
                log.error("无效的付款格式，必须以00结尾: {}", payload);
                return "ERROR|无效格式";
            }
            
            // 解析充电时长
            int chargingDuration = Integer.parseInt(durationPart);
            // 根据新的计费标准计算充电时间：1元=5分钟323
            // 假设 chargingDuration 是金额（分），转换为充电时长（秒）
            double amountYuan = chargingDuration / 100.0; // 转换为元
            int chargingMinutes = (int) (amountYuan * 5); // 1元=5分钟
            int chargingTimeInSeconds = chargingMinutes * 60; // 转换为秒
            log.info("付款金额: {}分({}元), 充电时长: {}分钟({}秒)", chargingDuration, amountYuan, chargingMinutes, chargingTimeInSeconds);
            // 向充电桩发送启动命令
            return String.format("%s.%d.%d", targetDevice, 0, chargingTimeInSeconds);
        } catch (NumberFormatException e) {
            log.error("付款信息解析失败: {}", payload, e);
            return "ERROR|无效数值";
        }
    }
    
    // 监控功率变化
    private void monitorPowerChange(String deviceId, int currentPower) {
        DeviceState state = deviceStates.get(deviceId);
        
        // 检查是否超过1800W
        if (currentPower > 1800) {
            String overloadMsg = String.format("%s.overload", deviceId);
            // 发送过载警告
            // mqttClient.publish(imei, overloadMsg);
            cutOffPower(deviceId);
            return;
        }
        
        // 检查功率上升超过50W
        int previousPower = state.getPreviousPower();
        if (previousPower > 0 && (currentPower - previousPower) > 50) {
            String changedMsg = String.format("%s.changed", deviceId);
            // 发送设备更换警告
            // mqttClient.publish(imei, changedMsg);
            stopPowerSupply(deviceId);
            return;
        }
        
        // 保存当前功率作为历史记录
        state.setPreviousPower(currentPower);
    }
    
    // 切断电源
    private void cutOffPower(String deviceId) {
        log.warn("切断设备 {} 电源", deviceId);
        // 实际断电操作
        // powerControlService.cutOff(deviceId);
    }
    
    // 停止供电
    private void stopPowerSupply(String deviceId) {
        log.warn("停止向设备 {} 供电", deviceId);
        // 停止供电操作
        // powerControlService.stopSupply(deviceId);
    }
    
    // 设备状态类
    private static class DeviceState {
        private long lastHeartbeat;
        private DeviceStatus status = DeviceStatus.OFFLINE;
        private int currentPower;
        private int previousPower;
        private long chargingTimeLeft;
        
        // Getters and Setters
        public long getLastHeartbeat() { return lastHeartbeat; }
        public void setLastHeartbeat(long lastHeartbeat) { this.lastHeartbeat = lastHeartbeat; }
        public DeviceStatus getStatus() { return status; }
        public void setStatus(DeviceStatus status) { this.status = status; }
        public int getCurrentPower() { return currentPower; }
        public void setCurrentPower(int currentPower) { this.currentPower = currentPower; }
        public int getPreviousPower() { return previousPower; }
        public void setPreviousPower(int previousPower) { this.previousPower = previousPower; }
        public long getChargingTimeLeft() { return chargingTimeLeft; }
        public void setChargingTimeLeft(long chargingTimeLeft) { this.chargingTimeLeft = chargingTimeLeft; }
    }
    
    // 设备状态枚举
    private enum DeviceStatus {
        OFFLINE,      // 离线
        ONLINE,       // 在线但未充电
        CHARGING,     // 充电中
        OVERLOAD,     // 过载
        NO_LOAD,      // 无负载
        CHANGED,      // 设备更换
        ERROR_DONE,   // 异常结束
        DONE          // 正常结束
    }
}